from flask import Flask, render_template, request
from flask_restful import Resource, Api
from vars import user_config
from pyspark.sql import SQLContext, SparkSession
from pyspark.sql import functions as F
from passwd import dbuser, dbpass, dbhost, dbport

app = Flask(__name__)
api = Api(app)

class Test_user(Resource):
    def post(self):
        spark = SparkSession. \
            Builder(). \
            appName('sql'). \
            master('local'). \
            getOrCreate()
        # mysql 配置(需要修改)
        prop = {'user': dbuser, 
                'password': dbpass,
                'driver': 'com.mysql.jdbc.Driver'}
        # database 地址(需要修改)
        url = 'jdbc:mysql://' + dbhost + ':' + dbport + '/ratemap'
        # 读取表，data1是用户表，data2是business表
        data1 = spark.read.jdbc(url=url, table='user', properties=prop)
        data2 = spark.read.jdbc(url=url, table='business', properties=prop)

        args = request.json

        print('===get args: {}'.format(args))

        ### 输入用户名称
        user = args['username']
        ### 获取所有用户的数据
        list = data1.collect()
        ### 创建三个字典，分别保存用户对应的粉丝、朋友和评价
        fans = {}
        friends = {}
        stars = {}
        ### 保存过程
        for i in list:
            fans[i.name] = i.fans
            friends[i.name] = i.friends
            stars[i.name] = i.average_stars
        ### 展示数据
        return {
            'fans': fans[user],
            'friends': friends[user],
            'stars': stars[user]
        }

api.add_resource(Test_user, '/user_analysis')

if __name__ == '__main__':
    app.run(debug=True, host=user_config['host'], port=user_config['port'])